﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using InsuranceCompany.Helpers;
using ClientNS = InsuranceCompany.Core.Domain.Client;
using PolicyC = InsuranceCompany.Core.Domain.InsuranceObjects.Policy;
using Event = InsuranceCompany.Core.Domain.Objects.Event;
using InsuranceEvent = InsuranceCompany.Core.Domain.InsuranceObjects.InsuranceEvent;
using InsuranceRisks = InsuranceCompany.Core.Domain.InsuranceArea.InsuranceRisks;
using InsuranceRisk = InsuranceCompany.Core.Domain.InsuranceArea.InsuranceRisk;
using AccidenP = InsuranceCompany.Core.Domain.InsuranceObjects.Accident;

namespace InsuranceCompany.Client
{
    public partial class Edit : InsuranceForm, InsuranceEditModuleInterface
    {
        private ClientNS.Client Client;
        private PolicyC SelectedPolicy;
        public Edit()
        {
            InitializeComponent();
        }
        public Edit(ref List<ObjectsCollection> objects)
        {
            InitializeComponent();
            this.Objects = objects;
            //this.Client = new ClientNS.Client();
        }
        public Edit(ref List<ObjectsCollection> objects, ClientNS.Client c)
        {
            InitializeComponent();
            this.radioButtonNaturalPerseon.Enabled = false;
            this.radioButtonJuridicalCLient.Enabled = false;
            this.Objects = objects;
            this.Client = c;
            string clientType = c.GetType().Name;
            if (clientType == "NaturalClient")
            {
                this.radioButtonNaturalPerseon.Checked = true;
                this.SetEnabledClientFields(true);
                ClientNS.NaturalClient client = (ClientNS.NaturalClient)c;
                this.NameVal.Text = client.Name;
                this.SurnameVal.Text = client.Surname;
                this.PatronimicVal.Text = client.Patronymic;
                this.PhoneVal.Text = client.Phone;
                this.EmailVal.Text = client.Email;
                this.AddressVal.Text = client.Adress;
                if (client.Gender == 0)
                {
                    this.GenderM.Checked = true;
                    this.GenderF.Checked = false;
                }
                else
                {
                    this.GenderF.Checked = true;
                    this.GenderM.Checked = false;
                }
                this.dateTimePickerBirthday.Value = client.Birthday;
                this.dateTimePickerDriverLicenceDate.Value = client.DriverLicensDate;
            }
            else if (clientType == "JuridicalClient")
            {
                this.radioButtonJuridicalCLient.Checked = true;
                this.SetEnabledClientFields(false);
                ClientNS.JuridicalClient client = (ClientNS.JuridicalClient)c;
                this.NameVal.Text = client.Name;
                this.SurnameVal.Text = client.Surname;
                this.PatronimicVal.Text = client.Patronymic;
                this.PhoneVal.Text = client.Phone;
                this.EmailVal.Text = client.Email;
                this.AddressVal.Text = client.Adress;
                if (client.Gender == 0)
                {
                    this.GenderM.Checked = true;
                    this.GenderF.Checked = false;
                }
                else
                {
                    this.GenderF.Checked = true;
                    this.GenderM.Checked = false;
                }
                this.CompanyNameVal.Text = client.CompanyName;
                this.CompanyIdVal.Text = client.CompanyIdentifier;
                this.DirectorVal.Text = client.Director.Name;
                this.AccountantVal.Text = client.Accountant.Name;
            }
            this.UpdateItemsListView();
        }
        private void SetEnabledClientFields(bool enabledNaturalClientFields)
        {
            this.dateTimePickerBirthday.Enabled = enabledNaturalClientFields;
            this.dateTimePickerDriverLicenceDate.Enabled = enabledNaturalClientFields;
            this.CompanyNameVal.Enabled = !enabledNaturalClientFields;
            this.CompanyIdVal.Enabled = !enabledNaturalClientFields;
            this.DirectorVal.Enabled = !enabledNaturalClientFields;
            this.AccountantVal.Enabled = !enabledNaturalClientFields;
        }
        private void RadioButtonNaturalPerseon_CheckedChanged(object sender, EventArgs e)
        {
            this.SetEnabledClientFields(true);
        }

        private void radioButtonJuridicalCLient_CheckedChanged(object sender, EventArgs e)
        {
            this.SetEnabledClientFields(false);
        }

        private void SaveItem(ClientNS.Client client) 
        {      
            if (FieldsValidation.IsValid())
            {
                ObjectsCollection clients = this.Objects.Find(x => x.GetName() == "Clients");
                if (this.Client == null)
                {
                    this.Client = client;
                    clients.Items.Add(client);
                }
                else 
                {
                    clients.Items.Remove(this.Client);
                    this.Client = client;
                    clients.Items.Add(client);
                }
                MessageBox.Show("Данные сохранены");
            }
        }
        private void SaveButtonClick(object sender, EventArgs e)
        {
            if ( this.radioButtonNaturalPerseon.Checked)
            {
                ClientNS.NaturalClient client = new ClientNS.NaturalClient();
                client.Name = this.NameVal.Text;
                client.Surname = this.SurnameVal.Text;
                client.Patronymic = this.PatronimicVal.Text;
                client.Phone = this.PhoneVal.Text;
                client.Email = FieldsValidation.CheckEmail(this.EmailVal.Text);
                client.Adress = this.AddressVal.Text;
                if (this.GenderM.Checked)
                    client.Gender = 0;
                else
                    client.Gender = 1;
                client.Birthday = this.dateTimePickerBirthday.Value;
                client.DriverLicensDate = this.dateTimePickerDriverLicenceDate.Value;

                // policies save
                this.SaveItem(client);
            }
            else
            {
                ClientNS.JuridicalClient client = new ClientNS.JuridicalClient();
                client.Name = this.NameVal.Text;
                client.Surname = this.SurnameVal.Text;
                client.Patronymic = this.PatronimicVal.Text;
                client.Phone = this.PhoneVal.Text;
                client.Email = FieldsValidation.CheckEmail(this.EmailVal.Text);
                client.Adress = this.AddressVal.Text;
                if (this.GenderM.Checked)
                    client.Gender = 0;
                else
                    client.Gender = 1;
                client.CompanyName = this.CompanyNameVal.Text;
                client.CompanyIdentifier = this.CompanyIdVal.Text;
                client.Director = new Core.Domain.Objects.Person(this.DirectorVal.Text);
                client.Accountant = new Core.Domain.Objects.Person(this.AccountantVal.Text);
                this.SaveItem(client);
            }
            this.radioButtonNaturalPerseon.Enabled = false;
            this.radioButtonJuridicalCLient.Enabled = false;
        }
        protected void CloseClick(object sender, EventArgs e)
        {
            this.Close();
        }
        private void AddPolicyButtonClick(object sender, EventArgs e)
        {
            if (this.Client != null)
            {
                List<ObjectsCollection> objects = this.Objects;
                Policy policyForm = new Policy(ref objects, this.Client);
                this.Hide();
                policyForm.ShowDialog();
                this.Objects = objects;
                this.Show();
                this.UpdateItemsListView();
            }
        }
        /*
        private void DeleteRiskButtonClick(object sender, EventArgs e)
        {
            this.IRisksAll.GetRisks().Remove(this.SelectedIRisk);
            this.UpdateItemsListView();
        }
        */
        private void UpdateItemsListView()
        {
            this.PoliciesListView.Items.Clear();
            foreach (Event item in this.Client.GetHistory().GetHistory())
            {
                string eventType = item.GetType().Name;
                if (eventType == "InsuranceEvent") 
                {
                    InsuranceEvent ie = (InsuranceEvent)item;
                    string insuranceDoc = ie.Document.GetType().ToString();
                    if (insuranceDoc == "InsuranceCompany.Core.Domain.InsuranceObjects.Policy")
                    {
                        PolicyC policy = (PolicyC)ie.Document;
                        ListViewItem listViewItem = new ListViewItem();
                        listViewItem.SubItems[0].Text = ie.GetId().ToString();
                        listViewItem.SubItems.Add(policy.CreateDate.ToShortDateString());
                        listViewItem.SubItems.Add(policy.PolicyPeriod.ToString());
                        if (policy.Type != null)
                            listViewItem.SubItems.Add(policy.Type.Name);
                        else
                            listViewItem.SubItems.Add("не выбрано");
                        listViewItem.SubItems.Add(policy.Price.ToString());
                        this.PoliciesListView.Items.Add(listViewItem);
                    }
                }
            }
        }

        private void PoliciesListViewItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (this.PoliciesListView.SelectedItems.Count == 1)
            {
                ListView.SelectedListViewItemCollection selectedItems = this.PoliciesListView.SelectedItems;
                int id = -1;
                foreach (ListViewItem item in selectedItems)
                {
                    id = Int32.Parse(item.SubItems[0].Text);
                    break;
                }
                InsuranceEvent ie = (InsuranceEvent)this.Client.GetHistory().GetHistory().Find(x => x.GetId() == id);
                PolicyC policy = (PolicyC)ie.Document;
                this.SelectedPolicy = policy;
                this.PayButton.Enabled = true;
                this.AccidentButton.Enabled = true;
            }
        }

        private void PayButtonClick(object sender, EventArgs e)
        {
            if (this.Client != null)
                this.ShowPayForm("Список всех выплат по полису", this.SelectedPolicy.GetId());
        }
        private void PayAllClick(object sender, EventArgs e)
        {
            if (this.Client != null)
                this.ShowPayForm("Список всех выплат по клиенту");
        }
        private void ShowPayForm(string title, int policyId = 0)
        {
            List<AccidenP> payment = new List<AccidenP>();
            foreach (Event item in this.Client.GetHistory().GetHistory())
            {
                string eventType = item.GetType().Name;
                if (eventType == "InsuranceEvent")
                {
                    InsuranceEvent ie = (InsuranceEvent)item;
                    //string insuranceEventDocType = ie.GetType().Name;
                    //if (insuranceEventDocType == "InsuranceEvent")
                    //{
                    
                    
                        PolicyC policy = (PolicyC)ie.Document;
                        foreach (Event aev in policy.GetHistory().GetHistory())
                        {
                            InsuranceEvent ev = (InsuranceEvent)aev;
                            if (ev.Document != null)
                            {
                                string insuranceEventDocType = ev.Document.GetType().Name;
                                if (insuranceEventDocType == "Accident")
                                {
                                    AccidenP accident = (AccidenP)ev.Document;
                                    if (accident.Result == "Принято" && (policyId == accident.Policy.GetId() || policyId == 0))
                                        payment.Add(accident);
                                }
                            }
                        }
                    
                   // }
                    /*
                    InsuranceEvent ie = (InsuranceEvent)item;
                    string insuranceEventType = ie.GetType().Name;
                    if (insuranceEventType == "Accident")
                    {
                        AccidenP accident = (AccidenP)ie.Document;
                        if (accident.Result == "Accepted" && ( policyId == accident.Policy.GetId() && policyId > 0) )
                            payment.Add(accident);
                    }
                    */
                }
            }
            if (payment.Count > 0) 
            {             
                ListForm listForm = new ListForm(payment, title);
                this.Hide();
                listForm.ShowDialog();
                this.Show();
                this.UpdateItemsListView();
            }
        }

        private void AccidentClick(object sender, EventArgs e)
        {
            List<ObjectsCollection> objects = this.Objects;
            Accident accidentForm = new Accident(ref objects, this.Client, this.SelectedPolicy);
            this.Hide();
            accidentForm.ShowDialog();
            this.Objects = objects;
            this.Show();
        }
    }
}
